const jwt = require('jsonwebtoken');

function verifiedFunction(req, res, next) {
  // console.log("hello")
  // Gather the jwt access token from the request header
  const authHeader = req.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1];
  // console.log(authHeader.split(' ')[1])
  if (token == null) return res.sendStatus(401); // if there isn't any token

  try {
    const verified = jwt.verify(token, 'This is the key and hello world');
    req.user = verified;
    // console.log(req.user)
    return next();
  } catch (error) {
    return res.status(400).send('Invalid token');
  }
}

function checkStore(req, res, next) {
  // Gather the jwt access token from the request header
  if (req.user.role === 'store' || req.user.role === 'admin') {
    return next();
  }
  return res.status(401).send('非店家账户');
}


function checkAdmin(req, res, next) {
  // Gather the jwt access token from the request header
  if (req.user.role === 'admin') {
    return next();
  }
  return res.status(401).send('非管理员账户');
}

module.exports = { verifiedFunction, checkAdmin, checkStore };
